import axios from "axios";
import {useEffect, useState} from "react";
import {notification} from "antd";

function usePublish(type) {//自定义hooks
    const {username}=JSON.parse(localStorage.getItem("token"))
    const[data,setData] = useState([])
    useEffect(()=>{
        axios.get(`/news?author=${username}&publishState=${type}&_expand=category`).then(res=>{
            setData(res.data)
        })
    },[type,username])
    const handlePublish = (id) => {
        setData(data.filter(item=>item.id!==id))
        axios.patch(`/news/${id}`,{
            "publishState":2
        }).then(res=>{
            notification.info({
                message: "通知",
                description:
                    `您可以在已上线中查看新闻`
            });
        })
    }
    const handleDelete = (id) => {
        setData(data.filter(item=>item.id!==id))
        axios.delete(`/news/${id}`).then(res=>{
            notification.info({
                message: `通知`,
                description:
                    `您已经删除了已下线的新闻`,
                placement:"bottomRight"
            });
        })
    }
    const handleSunset = (id) => {
        setData(data.filter(item=>item.id!==id))
        axios.patch(`/news/${id}`, {
            "publishState": 3,
        }).then(res=>{
            notification.info({
                message: `通知`,
                description:
                    `您可以到【发布管理/已下线】中查看您的新闻`,
                placement:"bottomRight"
            });
        })
    }
    return {
        data,
        handleDelete,
        handlePublish,
        handleSunset,
    }
}
export default usePublish;